<?php

namespace app\admin\controller\entrepot;

use app\admin\model\develop\Acuisitionscheme;
use app\admin\model\other\Colour;
use app\admin\model\statistics\Acquisitionschemedetail;
use app\admin\model\statistics\Materialplanaudit;
use app\admin\model\statistics\Orderdetail;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Process;

/**
 * 发料管理
 *
 * @icon fa fa-circle-o
 */
class Deliver extends Backend
{

    /**
     * Deliver模型对象
     * @var \app\admin\model\entrepot\Deliver
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $noNeedRight = ['check_info','getMaterialName'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\entrepot\Deliver;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['order', 'detail', 'employee', 'plan', 'colour'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->visible(['id', 'quantity', 'createtime', 'updatetime', 'status', 'delivertime', 'material_plan_id', 'order_detail_id']);
                $row->visible(['order']);
                $row->getRelation('order')->visible(['order_no', 'schedule']);
                $row->visible(['detail']);
                $row->getRelation('detail')->visible(['trademark_printing', 'abbreviation', 'quantity']);
                $row->visible(['employee']);
                $row->getRelation('employee')->visible(['name']);
                $row->visible(['plan']);
                $row->getRelation('plan')->visible(['materiallist','name']);
                $row->visible(['colour']);
                $row->getRelation('colour')->visible(['name']);
            }
            foreach ($list as $row) {
                $row->material_plan_name = Db::name('material_plan_audit')->where('id', 'eq', $row['material_plan_id'])->value('name');
                if(!$row->material_plan_name){
                    $row->material_plan_name = Db::name('material_plan')->where('id', 'eq', $row['material_plan_id'])->value('name');
                }
                $row->visible(['material_plan_name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加 by lhq
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $materiallist = '';
                if ($params['materiallist']) {
                    $materiallist = $params['materiallist'];
                    unset($params['materiallist']);
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    $deliver_id = $this->model->getLastInsID();
                    //循环插入子表
                    $materiallist = \GuzzleHttp\json_decode($materiallist, true);

                    foreach ($materiallist as $k => $v) {
                        $insert_data['deliver_id'] = $deliver_id;
                        $insert_data['material_id'] = $v['material_id'];
                        $insert_data['material_colour_id'] = $v['material_colour_id'];
                        $insert_data['weight'] = $v['weight'];
                        $model = new \app\admin\model\entrepot\Deliverdetail;
                        $inset_re = $model->save($insert_data);
                    }

//                    查找领料表数据
                    $acquisition_scheme = new Acuisitionscheme();
                    $acquisition_scheme_where['order_detail_id'] = $params['order_detail_id'];
                    $data = collection($acquisition_scheme->where($acquisition_scheme_where)->limit(1)->select())->toArray();

                    if (count($data) > 0) {
                        $acquisition_scheme_detail = new Acquisitionschemedetail();
                        //添加待领料记录
                        $insert_data['acquisition_scheme_id'] = $data[0]['id'];
                        $insert_data['employee_id'] = $data[0]['employee_id'];
                        $insert_data['quantity'] = $data[0]['quantity'];
                        $re = $acquisition_scheme_detail->save($insert_data);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
//                    p($row['quantity']);
                    if ($result) {
                        //计算物料重量数据
                        //数量*投料重量*（长档比例*物料比例 + 短档比例*物料比例）
                        //获取物料方案详情
                        $materialplan = new \app\admin\model\statistics\Materialplan;
                        $materialplan_where['id'] = $params['material_plan_id'];
                        $materialplan_data = collection($materialplan->where($materialplan_where)->limit(1)->select())->toArray();

//                        //如果审核表中不存在数据，则从物料方案表中获取（兼容一期旧数据）
                        if (!$materialplan_data){
                            $materialplan = new \app\admin\model\statistics\Materialplan;
                            $materialplan_where['id'] = $params['material_plan_id'];
                            $materialplan_where['status'] = 1;
                            $materialplan_data = collection($materialplan->where($materialplan_where)->limit(1)->select())->toArray();
                        }

                        $materiallist = [];
                        $long = '';
                        $short = '';
                        if (boolval($materialplan_data[0]['longlist'])) $long = \GuzzleHttp\json_decode($materialplan_data[0]['longlist'], true);

                        if (boolval($materialplan_data[0]['shortlist'])) $short = \GuzzleHttp\json_decode($materialplan_data[0]['shortlist'], true);

                        if ($long && $short) {
                            foreach ($long as $k => $v) {
                                foreach ($short as $k2 => $v2) {
                                    if ($v['material'] == $v2['material'] && $v['material_colour'] == $v2['material_colour']) {
                                        $data['weight'] = round($row['quantity'] * $materialplan_data[0]['feeding_weight']
                                            * ($materialplan_data[0]['long_ratio'] / 100 * $v['ratio'] / 100
                                                + $materialplan_data[0]['short_ratio'] / 100 * $v2['ratio'] / 100), 2);
                                        if (!isset($materiallist[$v2['material'] . $v2['material_colour']])) {
                                            $data['material'] = $v2['material'];
                                            $data['material_colour'] = $v2['material_colour'];
                                            $materiallist[$v2['material'] . $v2['material_colour']] = $data;
                                        } else {
                                            $materiallist[$v2['material'] . $v2['material_colour']]['weight'] = $data['weight'];
                                        }

                                        //  p('计算公式='.$cur_quantity.'*'.$materialplan_data[0]['feeding_weight'].
//                                        '*('.$materialplan_data[0]['long_ratio'].'/100*'.$v['ratio'].'/100
//                                            + '.$materialplan_data[0]['short_ratio'].'/100*'.$v2['ratio'].'/100)');

                                    } else { //添加两条

                                        $data['material'] = $v2['material'];
                                        $data['material_colour'] = $v2['material_colour'];
                                        $data['weight'] = round($row['quantity'] * $materialplan_data[0]['feeding_weight'] * $materialplan_data[0]['short_ratio'] / 100 * $v2['ratio'] / 100, 2);

                                        if (!isset($materiallist[$v2['material'] . $v2['material_colour']])) {
                                            $data['weight'] = $data['weight'];
                                            $materiallist[$v2['material'] . $v2['material_colour']] = $data;
                                        } else {
                                            foreach ($materiallist as $key => $val) {
                                                if ($val['material'] == $data['material'] && $val['material_colour'] == $data['material_colour']) {
                                                    $data['weight'] += $data['weight'];
                                                }
                                            }
                                        }

                                        $data2['material'] = $v['material'];
                                        $data2['material_colour'] = $v['material_colour'];
                                        $data2['weight'] = round($row['quantity'] * $materialplan_data[0]['feeding_weight'] * $materialplan_data[0]['long_ratio'] / 100 * $v['ratio'] / 100, 2);
                                        if (!is_set_material($data2, $materiallist)) {
                                            $data2['weight'] = $data2['weight'];
                                            $materiallist[$v['material'] . $v['material_colour']] = $data2;
                                        } else {
                                            foreach ($materiallist as $key => $val) {
                                                if ($val['material'] == $data2['material'] && $val['material_colour'] == $data2['material_colour']) {
                                                    $data['weight'] += $data2['weight'];
                                                }

                                            }
                                        }

                                    }
                                }
                            }
                        }
                        if ($long && !$short) {
                            foreach ($long as $k => $v) {
                                $data2['material'] = $v['material'];
                                $data2['material_colour'] = $v['material_colour'];
                                $data2['weight'] = round($row['quantity'] * $materialplan_data[0]['feeding_weight'] * $materialplan_data[0]['long_ratio'] / 100 * $v['ratio'] / 100, 2);
                                if (!is_set_material($data2, $materiallist)) {
                                    $data2['weight'] = $data2['weight'];
                                    $materiallist[$v['material'] . $v['material_colour']] = $data2;
                                } else {
                                    foreach ($materiallist as $key => $val) {
                                        if ($val['material'] == $data2['material'] && $val['material_colour'] == $data2['material_colour']) {
                                            $data['weight'] += $data2['weight'];
                                        }

                                    }
                                }
                            }
                        }
                        if (!$long && $short) {
                            foreach ($short as $k2 => $v2) {
                                $data['material'] = $v2['material'];
                                $data['material_colour'] = $v2['material_colour'];
                                $data['weight'] = round($row['quantity'] * $materialplan_data[0]['feeding_weight'] * $materialplan_data[0]['short_ratio'] / 100 * $v2['ratio'] / 100, 2);
                                if (!isset($materiallist[$v2['material'] . $v2['material_colour']])) {
                                    $data['weight'] = $data['weight'];
                                    $materiallist[$v2['material'] . $v2['material_colour']] = $data;
                                } else {
                                    foreach ($materiallist as $key => $val) {
                                        if ($val['material'] == $data['material'] && $val['material_colour'] == $data['material_colour']) {
                                            $data['weight'] += $data['weight'];
                                        }
                                    }
                                }
                            }
                        }

                        $deliver_data['materiallist'] = \GuzzleHttp\json_encode($materiallist, JSON_UNESCAPED_UNICODE);
                        $result = $row->allowField(true)->save($deliver_data);

                        //同步更新领料方案的物料方案id
                        Db::name('acquisition_scheme')->where('id', 'eq', $params['acquisition_scheme_detail_id'])->setField('material_plan_id', $params['material_plan_id']);

                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $type = $this->request->get("type");
        if ($row->materiallist) {
            $materialArr = json_decode($row->materiallist, true);
            if ($materialArr && is_array($materialArr)) {
                foreach ($materialArr as $k => $v) {

                    $materialArr[$k]['weight'] = round($v['weight']) / 1000;
                }
                $row->materiallist = json_encode($materialArr, JSON_UNESCAPED_UNICODE);
            }
//            p($row->materiallist);
        }
        if ($type == 'deliverdetail') {
            //'order','detail','employee','plan','colour'关联查询
            $res = Db::name('deliver')->alias('a')
                ->field('a.id,a.delivertime,a.quantity,a.status,o.order_no,m.trademark_printing,m.abbreviation,c.name as colour_name,e.name as employee_name,od.quantity as order_quantity')
                ->join('order o', 'a.order_id = o.id')
                ->join('material_plan m', 'a.material_plan_id = m.id')
//                ->join('material_plan_audit m', 'a.material_plan_id = m.id')
                ->join('colour c', 'a.colour_id = c.id')
                ->join('employee e', 'a.employee_id = e.id')
                ->join('order_detail od', 'a.order_detail_id = od.id')
                ->where('a.id="' . $ids . '"')
                ->find();
            $status = array(
                '0' => '待发料',
                '1' => '已发料',
                '2' => '退料'
            );
            $this->view->assign("res", $res);

            $this->view->assign("status", $status);
            return $this->view->fetch('entrepot/deliver/deliverdetail');
        } else {
            return $this->view->fetch();
        }
    }

    public function check_info()
    {
        $idsArr = explode(',', $this->request->post('ids'));
        //查询是否是是同一个员工
        $employeeList = $this->model->where('id', 'in', $idsArr)->group('employee_id')->column('status');
        if (count($employeeList) > 1) {
            $data['res'] = 0;
            $data['msg'] = '一次只能发放一个员工的物料';
            return json($data, JSON_UNESCAPED_UNICODE);
        }
        if ($employeeList[0] > 0) {
            $data['res'] = 0;
            $data['msg'] = '只能选择待发料数据';
            return json($data, JSON_UNESCAPED_UNICODE);
        }
        $data['res'] = 1;
        $data['msg'] = '校验通过';
        return json($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * 发料
     */
    public function deliver($ids = null)
    {
        $colour = new Colour();
        $result = true;
        $data['data'] = [];
        $idsArr = explode(',', $ids);
//         //查询是否是是同一个员工
//         $employeeList = $this->model->where('id','in',$idsArr)->group('employee_id')->column('status');
//         if(count($employeeList)>1){
//             $data['code'] = 0;
//             $data['msg'] = '一次只能发放一个员工的物料';
//             return json_encode($data);
//         }

//        if($employeeList[0]>0){
//            $data['res'] = 0;
//            $data['msg'] = '只能选择待发料数据';
//            return json_encode($data);
//        }
//        获取选中发货数
        $where['deliver.id'] = array('in', $idsArr);
        $this->buildparams($where);
        $deliverList = collection($this->model->alias('deliver')
            ->with(['order', 'detail', 'employee', 'plan'])
            ->where($where)
            ->select())->toArray();

        if ($this->request->isPost()) {
            $idsArr = explode(',', $this->request->post('ids'));

            Db::startTrans();
            try {
                //更新发货信息
                $upData['status'] = 1;
                $up_result = $this->model->where('id', 'in', $idsArr)->update($upData);

                if (!$up_result) {
                    $data['res'] = 0;
                    $data['msg'] = '发放失败，请稍候再试1';
                    Db::rollback();
                    return json($data);
                }

                foreach ($deliverList as $k => $v) {
                    //更新发料时间为当前时间
                    $this->model->where('id', 'eq', $v['id'])->setField('delivertime', time());

                    //更新领料明细状态为已发料
                    $ac = new Acquisitionschemedetail();
                    $ac->where('id', 'eq', $v['acquisition_scheme_detail_id'])->setField('status', 1);

                    //更新订单明细状态为已发料
                    $orderdetail = new Orderdetail();
                    $orderdetail->where('id', 'eq', $v['order_detail_id'])->setField('status', 2);

                }

                $data['res'] = 1;
                $data['msg'] = '发料成功！';
                Db::commit();
                return $this->success('发料成功');
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        foreach ($deliverList as $k => $v) {
   
            if (!isset($data['data']['info_list'][$v['order_id'] . $v['order_detail_id']])) {
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['order_no'] = $v['order']['order_no'];
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['trademark_printing'] = $v['detail']['trademark_printing'];
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['colour'] = $colour->where('id', 'eq', $v['detail']['colour_id'])->value('name');
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['employee'] = $v['employee']['name'];
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['quantity'] = $v['quantity'];
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['materiallist'] = [];
            } else {
                $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['quantity'] += $v['quantity'];
            }
            //组装打印数据
            $materiallist = json_decode($v['materiallist'], true);
            if (is_array($materiallist) && count($materiallist) > 0) {
                foreach ($materiallist as $k2 => $v2) {
                    if (!isset($data['data']['materiallist'][$v2['material'] . $v2['material_colour']])) {
                        $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['material'] = $v2['material'];
                        $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['material_colour'] = $v2['material_colour'];
                        $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['weight'] = $v2['weight'] / 1000;
                    } else {
                        $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['weight'] += $v2['weight'] / 1000;
                    }
                }
            }


        }
        $data['data']['delivertime'] = date('Y-m-d H:i:s');
        $data['res'] = 1;
        $data['msg'] = '打印数据';

        $this->view->assign('data', $data);
        $this->view->assign('ids', $ids);
        return $this->view->fetch();


//        p($ids);
//        $result = true;
//        $data['data'] = [];
//        $type = $this->request->request('type');
//
//        if(!$ids && !$type){
//            $data['code'] = 0;
//            $data['msg'] = '数据有误';
//            return json($data);
//        }
//        $idsArr = explode(',',$ids);
//        //查询是否是是同一个员工
//        $employeeList = $this->model->where('id','in',$idsArr)->group('employee_id')->column('status');
//
//        if(count($employeeList)>1){
//            $data['code'] = 0;
//            $data['msg'] = '一次只能发放一个员工的物料';
//            return json($data);
//        }
//
//        if($employeeList[0]>0){
//            $data['code'] = 0;
//            $data['msg'] = '只能选择待发料数据';
//            return json($data);
//        }
//
//        Db::startTrans();
//        try {
//
//            //更新发货信息
//            $upData['status'] = 1;
//            $up_result = $this->model->where('id','in',$idsArr)->update($upData);
//            if(!$up_result){
//                $data['code'] = 0;
//                $data['msg'] = '发放失败，请稍候再试';
//                Db::rollback();
//                return json($data);
//            }
//
//
//            $where['deliver.id'] =array('in',$idsArr);
//            $this->buildparams($where);
//            $deliverList = collection($this->model->alias('deliver')
//                ->with(['order','detail','employee','plan'])
//                ->where($where)
//                ->select())->toArray();
//            $colour = new Colour();
//            foreach ($deliverList as $k=>$v){
//                 //更新领料明细状态为已发料
//                $ac = new Acquisitionschemedetail();
//                $ac->where('id','eq',$v['acquisition_scheme_detail_id'])->setField('status',1);
//
//                if($type != 1){
//                    //更新订单明细状态为已发料
//                    $orderdetail = new Orderdetail();
//                    $orderdetail->where('id','eq',$v['order_detail_id'])->setField('status',2);
//
//                    //更新发料时间为当前时间
//                    $this->model->where('id','eq',$v['id'])->setField('delivertime',time());
//                }
//
//
////                if(!isset($data['data']['info_list'][$v['order']['order_no']])){
//                if(!isset($data['data']['info_list'][$v['order_id'].$v['order_detail_id']])){
//                    $data['data']['info_list'][$v['order_id'].$v['order_detail_id']]['order_no'] = $v['order']['order_no'];
//                    $data['data']['info_list'][$v['order_id'].$v['order_detail_id']]['trademark_printing'] = $v['detail']['trademark_printing'];
//                    $data['data']['info_list'][$v['order_id'].$v['order_detail_id']]['colour'] = $colour->where('id','eq',$v['detail']['colour_id'])->value('name');
//                    $data['data']['info_list'][$v['order_id'].$v['order_detail_id']]['employee'] = $v['employee']['name'];
//                    $data['data']['info_list'][$v['order_id'].$v['order_detail_id']]['quantity'] = $v['quantity'];
//                    $data['data']['info_list'][$v['order_id'].$v['order_detail_id']]['materiallist'] = [];
//                }else{
//                    $data['data']['info_list'][$v['order']['order_no']]['quantity'] += $v['quantity'];
//                }
//                //组装打印数据
//                $materiallist = json_decode($v['materiallist'],true);
//                if(is_array($materiallist) && count($materiallist)>0){
//                    foreach ($materiallist as  $k2=>$v2){
//                        if(!isset($data['data']['materiallist'][$v2['material'].$v2['material_colour']])){
//                            $data['data']['materiallist'][$v2['material'].$v2['material_colour']]['material'] = $v2['material'];
//                            $data['data']['materiallist'][$v2['material'].$v2['material_colour']]['material_colour'] = $v2['material_colour'];
//                            $data['data']['materiallist'][$v2['material'].$v2['material_colour']]['weight'] = $v2['weight'];
//                        }else{
//                            $data['data']['materiallist'][$v2['material'].$v2['material_colour']]['weight'] += $v2['weight']/1000;
//                        }
//                    }
//                }
//                $data['data']['delivertime'] = date('Y-m-d H:i:s');
//            }
//
//             if($result){
//                 if($type ==1){
//                     $data['code'] = 1;
//                     $data['msg'] = '打印数据';
//                     Db::rollback();
//                     return json($data);
//
//                 }else{
//                     Db::commit();
//                 }
//
//             }else{
//                 $data['code'] = 0;
//                 $data['msg'] = '发料失败';
//                 Db::rollback();
//                 return json($data);
//
//             }
//            Db::rollback();
//        } catch (ValidateException $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        } catch (PDOException $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * 发料
     */
    public function set_detail($ids = null)
    {
        $result = true;
        $data['data'] = [];
        if (!$ids) {
            $data['code'] = 0;
            $data['msg'] = '数据有误';
            return json($data);
        }

        $idsArr = explode(',', $ids);
        //查询是否是是用一个员工
        $employeeList = $this->model->where('id', 'in', $idsArr)->group('employee_id')->column('status');

        if (count($employeeList) > 1) {
            $data['code'] = 0;
            $data['msg'] = '一次只能发放一个员工的物料';
            return json($data);
        }
        if ($employeeList[0] > 0) {
            $data['code'] = 0;
            $data['msg'] = '只能选择待发料数据';
            return json($data);
        }

        Db::startTrans();
        try {
            //更新发货信息
            $upData['status'] = 1;
            $up_result = $this->model->where('id', 'in', $idsArr)->update($upData);
            if (!$up_result) {
                $data['code'] = 0;
                $data['msg'] = '发放失败，请稍候再试';
                Db::rollback();
                return json($data);
            }

            $where['deliver.id'] = array('in', $idsArr);
            $this->buildparams($where);
            $deliverList = collection($this->model->alias('deliver')
                ->with(['order', 'detail', 'employee', 'plan'])
                ->where($where)
                ->select())->toArray();
            $colour = new Colour();
//            p($deliverList);
            foreach ($deliverList as $k => $v) {
                //更新领料明细状态为已发料
                $ac = new Acquisitionschemedetail();
                $ac->where('id', 'eq', $v['acquisition_scheme_detail_id'])->setField('status', 1);

                //更新订单明细状态为已发料
                $orderdetail = new Orderdetail();
                $orderdetail->where('id', 'eq', $v['order_detail_id'])->setField('status', 2);

                //更新发料时间为当前时间
                $this->model->where('id', 'eq', $v['id'])->setField('delivertime', time());
//p($v);
//                if(!isset($data['data']['info_list'][$v['order']['order_no']])){
                if (!isset($data['data']['info_list'][$v['order_id'] . $v['order_detail_id']])) {
                    $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['order_no'] = $v['order']['order_no'];
                    $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['trademark_printing'] = $v['detail']['trademark_printing'];
                    $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['colour'] = $colour->where('id', 'eq', $v['detail']['colour_id'])->value('name');
                    $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['employee'] = $v['employee']['name'];
                    $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['quantity'] = $v['quantity'];
                    $data['data']['info_list'][$v['order_id'] . $v['order_detail_id']]['materiallist'] = [];
                } else {
                    $data['data']['info_list'][$v['order']['order_no']]['quantity'] += $v['quantity'];
                }
                //组装打印数据
                $materiallist = json_decode($v['materiallist'], true);
                if (is_array($materiallist) && count($materiallist) > 0) {
                    foreach ($materiallist as $k2 => $v2) {
                        if (!isset($data['data']['materiallist'][$v2['material'] . $v2['material_colour']])) {
                            $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['material'] = $v2['material'];
                            $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['material_colour'] = $v2['material_colour'];
                            $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['weight'] = $v2['weight'];
                        } else {
                            $data['data']['materiallist'][$v2['material'] . $v2['material_colour']]['weight'] += $v2['weight'];
                        }
                    }
                }
                $data['data']['delivertime'] = date('Y-m-d H:i:s');
            }
//            Db::rollback();
//            p($data);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '发料成功';
            return json($data);
        } else {
            $data['code'] = 0;
            $data['msg'] = '发料失败';
            return json($data);
        }

    }

    /**
     * @return void
     * 退料
     */
    public function withdraw($ids = '')
    {
        $result = array(
            'type' => 0,
            'msg' => '操作失败！'
        );
        $data['data'] = [];
        $ids = explode(',', $ids);
        if (!$ids) return json($result,);

        //只有待发料状态才能退料
        $where['id'] = array('in', $ids);
        $where['status'] = array('neq', 1);
        $re = $this->model->where($where)->count();
        $result['msg'] = '只有已发料状态才能退料';
        if ($re > 0) return json($result);

        Db::startTrans();

        //更新状态
        $upWhere['id'] = array('in', $ids);
        $res = $this->model->where($upWhere)->setField('status', 2);

        $deliverArr = Db::name('deliver')->where($upWhere)->select();

        $upData = [];
        foreach ($deliverArr as $k => $v) {
            $cumulative_quantity = Db::name('order_detail')->where('id', 'eq', $v['order_detail_id'])->value('cumulative_quantity');
//            p($cumulative_quantity);
            $where2['id'] = $v['order_detail_id'];
            $item['status'] = 2;

            $item['cumulative_quantity'] = $cumulative_quantity - $v['quantity'];
//            p($cumulative_quantity.'||'.$v['quantity']);
            $res2 = Db::name('order_detail')->where($where2)->update($item);


        }

        //跟新领料明细表状态为退料
        $acquisitionSchemeDetailModel = new Acquisitionschemedetail();
        $acquisition_scheme_detail_ids = $this->model->where($upWhere)->column('acquisition_scheme_detail_id');
        $acquisitionSchemeDetailModel->where('id', 'in', $acquisition_scheme_detail_ids)->setField('status', 2);
        //更新领料主表状态为退料
        $acuisitionschemeModel = new Acuisitionscheme();
        $acquisition_scheme_ids = $this->model->where($upWhere)->column('acquisition_scheme_id');
        $acuisitionschemeModel->where('id', 'in', $acquisition_scheme_ids)->setField('status', 3);

        $result['type'] = 1;
        $result['msg'] = '操作成功';
        Db::commit();
        return json($result);

    }

    public function getMaterialName()
    {
        $id = $this->request->get("id");
        //获取物料方案信息
        $materialPlanInfo = Db::name('order_detail')->where('id', 'eq', $id)->find();
        //根据商标印字和色号查找物料方案
//p($materialPlanInfo);
        $page_arr = [];
        $where['status'] = ['neq',0];
        $where['trademark_printing'] = $materialPlanInfo['trademark_printing'];
        $where['colour_id'] = $materialPlanInfo['colour_id'];
        $data = Db::table('fa_material_plan')->where($where)->field(['id', 'name'])->select();
        if (!$data){
            $data = Db::table('fa_material_plan_audit')->where($where)->field(['id', 'name'])->select();
        }

        $data_count = count($data);
        foreach ($data as $key => $val) {
            $page_arr[$key]['id'] = $data[$key]['id'];
            $page_arr[$key]['name'] = $data[$key]['name'];
        }
        $page_arr = formatArray($page_arr);
        $result = array(
            "list" => $page_arr,
            'total' => $data_count
        );

        return $result;
    }

}
